package org.example.service.impl;

import org.example.service.FuncApi;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Map;

@Component
public class StrategyFactory implements InitializingBean{

    @Autowired
    private ApplicationContext applicationContext;

    //策略map
    public static Map<String,FuncApi> strategyMaps = new HashMap<>();

    //根据功能名称获取对应的实现类进行处理
    public FuncApi getApiByFuncName(String funcName) throws Exception{
        FuncApi api = strategyMaps.get(funcName);
        if(null==api){
            throw new Exception("not matched api");
        }
        return api;
    }

    //启动时将所有处理类加载好由spring进行管理
    @Override
    public void afterPropertiesSet() throws Exception {
        Map<String, FuncApi> beansOfFuncType = applicationContext.getBeansOfType(FuncApi.class);
        for(Map.Entry<String,FuncApi> entry:beansOfFuncType.entrySet()){
            strategyMaps.put(entry.getKey(),entry.getValue());
        }
    }
}